package com.david.viewtest.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.david.viewtest.R
import java.io.File

/**
 * 文本label与本地iconLabel及云端icon共存的labelView
 * textView添加label参考：[com.david.viewtest.view.TextViewWithLabels]
 */
class MultiLabelView(context: Context, attrs: AttributeSet): View(context, attrs) {
    var paint = Paint()

    var itemHeight = 0
    var itemSpace = 6

    var textStartY = 0f

    var items = arrayListOf(
        MultiLabelItem(imgRes = R.mipmap.ic_prize),
        MultiLabelItem(labelText = "爆",labelTextColor =Color.RED, labelBgColor = Color.YELLOW,  ),
        MultiLabelItem(imgRes = R.mipmap.ic_prize),
        MultiLabelItem(labelText = "奖",labelTextColor =Color.BLUE, labelBgColor = Color.GREEN,  ),
        MultiLabelItem(imgUrl = "https://zeekrlife-oss-test.lkhaowu.com/IMAGE/1/client/1468049848863477760/zeekrlife-mp-osp/20240415/b2c3900d7ab34fea9005a1c11384daa3.jpg"),
        MultiLabelItem(labelText = "热",labelTextColor =Color.BLUE, labelBgColor = Color.GREEN,  ),
        MultiLabelItem(imgUrl = "https://zeekrlife-oss-test.lkhaowu.com/IMAGE/1/manage/731/zeekrlife-mp-osp/20240125/674ecba33e234c42a6b5583d0e9cbc97.jpg"),
        MultiLabelItem(imgUrl = "https://zeekrlife-oss-test.lkhaowu.com/IMAGE/1/client/1468049848863477760/zeekrlife-mp-osp/20240415/fd6a9799faad4ac1b9130bf30b674a68.jpg"),
        MultiLabelItem(imgUrl = "https://zeekrlife-oss-test.lkhaowu.com/IMAGE/1/client/1468049848863477760/zeekrlife-mp-osp/20240415/e6dcf954d83a4878ab9f396215733fa5.jpg"),
    )


    init {
        paint.color = Color.BLACK
        paint.textSize = 25f

        items.forEach {
            if (it.imgRes > 0) {
                it.imgBitmap = BitmapFactory.decodeResource(context.resources, it.imgRes)
            } else if (!it.imgUrl.isNullOrEmpty()) {
                Glide.with(this).downloadOnly()
                    .load(it.imgUrl)
                    .listener(object: RequestListener<File> {

                        override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>, isFirstResource: Boolean): Boolean {
                            return true
                        }

                        override fun onResourceReady(resource: File, model: Any, target: Target<File>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                            it.imgBitmap = BitmapFactory.decodeFile(resource.path)
                            requestLayout()
                            return true
                        }

                    }).preload()
            }
        }
    }


    private var left = 0
    private var tempItemWidth = 0//img/text的临时值
    private var tempTextWidth = 0//img/text的临时值

    private var viewWidth = 0
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (visibility == GONE) {
            return
        }


        val height = layoutParams.height

        itemHeight = layoutParams.height - paddingTop - paddingBottom

        left = paddingStart


        for ((index, item) in items.withIndex()) {
            if (item.imgBitmap != null) {
                tempItemWidth = (item.imgBitmap!!.width.toFloat() / item.imgBitmap!!.height * height).toInt()
                item.itemLeft = left
                item.itemRight = left + tempItemWidth

            } else if (!item.labelText.isNullOrEmpty()) {//非icon标签默认为文字标签
                tempTextWidth = paint.measureText(item.labelText).toInt()
                tempItemWidth = height

                item.itemLeft = left
                item.itemRight = left + height

                item.itemTextLeft = left.toFloat() + (height - tempTextWidth) / 2
            } else {
                tempItemWidth = 0
            }

            if (index == items.size - 1) {
                viewWidth = left + tempItemWidth + paddingEnd
            }
            if (item.imgBitmap != null || !item.labelText.isNullOrEmpty()) {
                left += tempItemWidth + itemSpace
            }

        }


        super.setMeasuredDimension(viewWidth, layoutParams.height)

        if (textStartY == 0f) {
            textStartY = measuredHeight / 2f - (paint.descent() + paint.ascent()) / 2f
        }
    }


    private var tempDstRect = Rect()
    private var tempBitmapRect = Rect()
    override fun onDraw(canvas: Canvas) {
        //super.onDraw(canvas)
        for (item in items) {
            if (item.imgBitmap == null && item.labelText.isNullOrEmpty()) {
                continue
            }
            if (item.imgBitmap != null) {
                tempBitmapRect.left = 0
                tempBitmapRect.top = 0
                tempBitmapRect.right = item.imgBitmap!!.width
                tempBitmapRect.bottom = item.imgBitmap!!.height

                tempDstRect.left = item.itemLeft ?: 0
                tempDstRect.top = 0
                tempDstRect.right = item.itemRight ?: 0
                tempDstRect.bottom = height

                canvas.drawBitmap(item.imgBitmap!!, tempBitmapRect, tempDstRect, paint)

            } else if (!item.labelText.isNullOrEmpty())  {
                if (item.labelBgColor != null) {
                    paint.color = item.labelBgColor!!

                    tempDstRect.left = item.itemLeft ?: 0
                    tempDstRect.top = 0
                    tempDstRect.right = item.itemRight ?: 0
                    tempDstRect.bottom = height

                    canvas.drawRect(tempDstRect, paint)
                }


                paint.color = item.labelTextColor ?: Color.BLACK
                //val x = width / 2f - paint.measureText(item) / 2f //用于绘制在屏幕横向中间
                //val y = height / 2f - (paint.descent() + paint.ascent()) / 2f
                canvas.drawText(item.labelText!!, item.itemTextLeft?:0f, textStartY, paint)
            }
        }
    }


    data class MultiLabelItem(
        //icon相关resId/url
        var imgRes: Int = -1,//本地icon资源id
        var imgUrl: String? = null,//云端icon

        //文本label相关属性
        var labelText: String? = null,//文本标签
        var labelTextColor: Int? = null,
        var labelBgColor: Int? = null,
    ) {
        //view中自动设置，
        var imgBitmap: Bitmap? = null//存储通过imgRes获取的bitmap，不需要外部传
        var itemLeft: Int? = 0//标签绘制的左起点,外部不需要传
        var itemRight: Int? = 0//标签绘制的右终点,外部不需要传，此值+paddingRight为view宽度
        var itemTextLeft: Float? = 0f//文本标签时绘制的左起点
    }
}